package com.example.yy.usbcameratest;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.arcsoft.face.ErrorInfo;
import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.LivenessParam;
import com.arcsoft.face.VersionInfo;
import com.arcsoft.face.enums.DetectFaceOrientPriority;
import com.arcsoft.face.enums.DetectMode;
import com.example.yy.usbcameratest.common.Constants;
import com.example.yy.usbcameratest.util.SharedUtil;
import com.example.yy.usbcameratest.view.SelectDialog;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity implements CameraPreview.FeedbackListener {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }
    private static final String TAG = MainActivity.class.getSimpleName();
    CameraPreview cp;
    TextView tv;
    FaceEngine faceEngine;
    private int faceEngineCode;
    private int subSetThreshold = 50;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        subSetThreshold = SharedUtil.getValue(this,SharedUtil.ArcSost_threshold,50, SharedUtil.ShareType.INTEGER);
       tv  = (TextView) findViewById(R.id.sample_text);
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                int code = FaceEngine.activeOnline(MainActivity.this, Constants.APP_ID,Constants.SDK_KEY);
                emitter.onNext(code);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer activeCode) {
                if (activeCode == ErrorInfo.MOK) {
                    tv.setText(getString(R.string.active_success));
                    initEngine();

                } else if (activeCode == ErrorInfo.MERR_ASF_ALREADY_ACTIVATED) {
                    tv.setText(getString(R.string.already_activated));
                    initEngine();
                } else {
                    tv.setText(getString(R.string.active_failed, activeCode));
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });


        // Example of a call to a native method

        tv.setText(stringFromJNI());

        cp = (CameraPreview) findViewById(R.id.cp);

        cp.setFeedbackTxtListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //加载菜单文件
        getMenuInflater().inflate(R.menu.title_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    boolean flag = true;

    LivenessParam  livenessParam = new LivenessParam(0.5f,0.7f);
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.set_throld:
                Toast.makeText(this, "参数设置", Toast.LENGTH_SHORT).show();
                subSetThreshold = SharedUtil.getValue(this,SharedUtil.ArcSost_threshold,50, SharedUtil.ShareType.INTEGER);
                showInputDialog(this);
                break;
                case R.id.resolution:
                    SelectDialog selectDialog = SelectDialog.newInstance();
                    selectDialog.show(getSupportFragmentManager(),"select");
                    selectDialog.setSelectedListener(new SelectDialog.OnSelectedListener() {
                        @Override
                        public void makeYourChoice(int res) {
                            Log.i(TAG,"res="+res);
                            SharedUtil.setSharedprefer(SharedUtil.USB_RESOLUTION,res,MainActivity.this.getApplicationContext());
                            finish();

                        }
                    });
                break;
            case R.id.set_encrypt:
                flag = !SharedUtil.getValue(getApplicationContext(),SharedUtil.encrypt,true, SharedUtil.ShareType.BOOLEAN) ;
                Log.i(TAG,"是否开启加密："+flag);
                SharedUtil.setSharedprefer(SharedUtil.encrypt,flag,getApplicationContext());
                Toast.makeText(this, flag?"开启加密":"不开启加密", Toast.LENGTH_SHORT).show();
                finish();
                System.exit(0);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    private void showInputDialog(final Context context){

        final EditText edit = new EditText(context);
        edit.setHint("输入0-100整数");
        edit.setInputType(InputType.TYPE_CLASS_NUMBER);
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
        //设置对话框标题
        builder.setTitle("请输入活体阈值");
        edit.setText(String.valueOf(subSetThreshold));
        builder.setView(edit);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String str = edit.getText().toString().trim();
                String regx = "^\\d{1,3}$";
                Pattern pattern = Pattern.compile(regx);
                Matcher matcher = pattern.matcher(str);
                if (matcher.matches() ){
                    int threshold = Integer.parseInt(str);
                    if (threshold>100){
                        threshold = 100;
                    }
                    SharedUtil.setSharedprefer(SharedUtil.ArcSost_threshold,threshold,context.getApplicationContext());
                    subSetThreshold = threshold;
                    Toast.makeText(context.getApplicationContext(), "你输入的是: " +str , Toast.LENGTH_SHORT).show();
                    setArcsoftThreshold();

                }else{
                    Toast.makeText(context.getApplicationContext(), "输入不合法"+str, Toast.LENGTH_SHORT).show();

                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(context.getApplicationContext(), "你点了取消", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setCancelable(true);
        android.app.AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private void setArcsoftThreshold() {
        float value = subSetThreshold/100.0f;
        Log.i(TAG, "手动设置检活阈值="+value);
        livenessParam.setRgbThreshold(value);
        if (faceEngine !=null){
        float rgbThreshold = livenessParam.getRgbThreshold();
            Log.i(TAG,String.format("设置阈值为%f",rgbThreshold));
        int setCode= faceEngine.setLivenessParam(livenessParam);
        if (setCode!= ErrorInfo.MOK){
            Toast.makeText(this, "设置阈值不成功", Toast.LENGTH_SHORT).show();
        }
        }else{
            Log.i(TAG,"未设置成功，因为faceEninge==null");
        }
    }

    private void initEngine() {
        faceEngine = new FaceEngine();
        faceEngineCode = faceEngine.init(this, DetectMode.ASF_DETECT_MODE_IMAGE, DetectFaceOrientPriority.ASF_OP_ALL_OUT,
                16, 10, FaceEngine.ASF_FACE_RECOGNITION | FaceEngine.ASF_FACE_DETECT | FaceEngine.ASF_AGE | FaceEngine.ASF_GENDER | FaceEngine.ASF_FACE3DANGLE | FaceEngine.ASF_LIVENESS);
        VersionInfo versionInfo = new VersionInfo();
        setArcsoftThreshold();
        faceEngine.getVersion(versionInfo);

        Log.i(TAG, "initEngine: init: " + faceEngineCode + "  version:" + versionInfo+ " _rgbThreshold="+livenessParam.getRgbThreshold());

        if (faceEngineCode != ErrorInfo.MOK) {
            tv.setText(getString(R.string.init_failed, faceEngineCode));
        }
        cp.transferFaceEngine(faceEngine);
    }
    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
    /**
     * 销毁引擎
     */
    private void unInitEngine() {
        if (faceEngine != null) {
            faceEngineCode = faceEngine.unInit();
            faceEngine = null;
            Log.i(TAG, "unInitEngine: " + faceEngineCode);
        }
    }

    @Override
    protected void onDestroy() {
        unInitEngine();
        super.onDestroy();
    }

    @Override
    public void feedbackTxt(final SpannableStringBuilder stringBuilder) {
        Log.i(TAG,"收到回调文本显示："+stringBuilder.toString());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv.setText(stringBuilder);
            }
        });

    }
}
